package org.uiot.protocol.group

import org.uiot.protocol.codec.BitOutputStream
import org.uiot.protocol.codec.BitSource
import org.uiot.protocol.codec.CachedRule

class CachedSequence implements Groupable, SequenceTraits, Comparable, Serializable {

    /**
     * 隶属（结构/编组）代码
     */
    Integer parentCode

    /**
     * 缓存的（编解码）规则
     */
    CachedRule cachedRule

    CachedSequence(Map p) {
        this(p.part, p.parentType, p.parentCode, p.serialNo, p.dataIdentifier, p.name, p.ruleCode)
    }

    CachedSequence(org.uiot.protocol.PacketTraits.Part part, Subjection parentType, Integer parentCode, Integer serialNo, String dataIdentifier, String name, String ruleCode) {
        this.part = part
        this.parentType = parentType
        this.parentCode = parentCode
        this.serialNo = serialNo
        this.dataIdentifier = dataIdentifier
        this.name = name
        this.ruleCode = ruleCode
    }

    @Override
    void decode(BitSource bitSource, Map contents) {
        contents[dataIdentifier] = cachedRule.decode(bitSource)
    }

    @Override
    void encode(BitOutputStream bitOutput, Map contents) {
        cachedRule.encode(bitOutput, contents[dataIdentifier])
    }

    @Override
    int compareTo(Object o) {
        if(o instanceof SequenceTraits) {
            return serialNo <=> o.serialNo
        }
        return 0
    }
}